import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'
import store from '../store'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login',
  },
  {
    path: '/vmodel',
    name: 'vmodel',
    meta: {
      auth: false,
      title: 'vmodel',
    },
    component: () => import('../views/v-model/index.vue'),
  },
  {
    path: '/login',
    name: 'login',
    meta: {
      auth: false,
      title: '登陆',
    },
    component: () => import('../views/Login.vue'),
  },
  {
    path: '/layout',
    name: 'layout',
    component: () => import('../layout/index.vue'),
    children: [
      {
        path: 'home',
        name: 'home',
        meta: {
          // 导航元信息
          auth: true, // 需要判断token才能进入页面
          title: '首页',
        },
        component: HomeView,
      },
      {
        path: 'cart',
        name: 'cart',
        meta: {
          auth: true, // 需要判断token才能进入页面
          title: '购物车',
        },
        component: () => import('../views/Cart.vue'),
      },
      {
        path: 'classify',
        name: 'classify',
        meta: {
          auth: true, // 需要判断token才能进入页面
          title: '分类',
        },
        component: () => import('../views/Classify.vue'),
      },
    ],
  },
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes,
})

// 在这个导航函数中，可以拦截路由，判断用户是否登陆，
// 如果没有登陆，就进入登陆页面，如果登陆了，就next往下走

// 导航守卫效果
router.beforeEach((to, from, next) => {
  // console.log('from', from) // 从哪来
  // console.log('to:', to) // 到哪去
  // true 说明需要token. token存在哪儿？
  document.title = to.meta.title
  if (to.meta.auth) {
    const token = store.state.token
    if (token) {
      next()
    } else {
      next({
        path: '/login',
      })
    }
  } else {
    next()
  }
})

export default router
